var final_element_index;
var indexes_array=Array();
var new_index=0;
var map = null;
var marker=null;
/* 
	Generates the mt single_compound_element list.
*/
function mt_single_compound(url_read, url_write, mql, properties, display_num,flag){
	final_element_index = 0;
	// Get the information from freebase
	perform_freebase_read(
		url_read,
		mql,
		function (msg) {
		
			var topic = null;
			topic = msg.result[0];
	        if (!topic) return;
	        
	        var h_topics = '';
	        
	        // Go through and get all of the topics and add them to the list
	        properties.parent_list = $('#list_vals');
	        var topics = msg.result;
	       	if(flag)
			{
				var j = 0;
	        	for(var i=0; i<topics.length; i++) {
				
					var no_headquarters=topics[i];
					var info=no_headquarters["/business/company/headquarters"];
					var len=no_headquarters["/business/company/headquarters"].length;
					
					if(parseInt(len) > 0) 
					{
							//donothing					
					} 
					else 
					{
						if(parseInt(len) < 0 )
						{
							//donothing
						}
						else
						{
							j++;
							indexes_array.push(i);
							
						}
					}
	        	}
				$("#num_companies").text(j);
				var num_companies=j;
				//no_headquarters["/business/company/headquarters"].length;
				// Add the elements to the queue	        
				var j=0;
				for(var i=0; i<topics.length; i++){
					var no_headquarters=topics[i];
					var info=no_headquarters["/business/company/headquarters"];
					var len=no_headquarters["/business/company/headquarters"].length;
					
					if(parseInt(len) > 0) 
					{
							//donothing					
					} 
					else 
					{
						if(parseInt(len) < 0 )
						{
							//donothing
						}
						else
						{
							
							if( j < display_num){
								
								//addElement(topics, properties, i, num_companies,flag);
								addElement(topics, properties, i, display_num,flag);
								j++;
							}
							else{
								break;
							}
						}
					}
					
					
				}
			}
			else
			{
				var num_remaining_topics = topics.length;
				var num_topics_string = ''+num_remaining_topics;
				$("#num_topics").text(num_topics_string);
				
				// Create indexes that randomize the ordering of the query results:
				var random_indexes = [];
				for(var i=0; i<topics.length; i++){
					random_indexes[i] = i;
				}
				//fisherYates(random_indexes);
				
				// Add the elements to the queue	        
				for(var i=0; i<display_num && i<random_indexes.length; i++){
					addElement(topics, properties, random_indexes, display_num);
				}
			}
		},
		function(m){}
	);

}

/* 
	Adds a single element to the bottom of the list
 */
function addElement(element_list, properties, indexes, display_num,flag){
	var index = final_element_index + 1;
	if(!flag)
	{
		var element = element_list[indexes[index]];
	}
	else
	{
		var element = element_list[indexes];
	}
	var name = element.name;
	var guid = element.id;
	var id = replaceAll(name, ' ', '-');
	id = id.replace('.', '')
	id = id.replace(',', '')
	id = id.replace('&amp;', '')
	id = id.replace("'", '')
	var data = element["/business/company/headquarters"];
	var type=element.type;
	var post_command = properties.post_command;
	var topic1_guid = properties.topic1_guid; 
	var topic1_property = properties.topic1_property;
	var submit1_name = properties.submit1_name;
	var submit1_id = properties.submit1_id;
	var submit2_name = properties.submit2_name;
	var submit2_id = properties.submit2_id;
	var parent_list = properties.parent_list;
	
	// Data that is needed to generate text for the box        	
	//var data = Object;
	//data.website = website;
	
	// Create the element
	var e_box_text = '';
	var address = '';
	var address_guid = '';
	if(data.length > 0){
		var hq = data[0];
		address_guid = hq.guid;
		address = getAddress(hq);
		e_box_text += properties.generate_mt_text(name, address); // dynamically generate text for the text box.
	} else {
		e_box_text += "Company does not have a location."
	}
	
	var e_html = '<div id="id_'+id+'">';
	if(!flag)
	{
		e_html += '<div style="width:400px;height:100px;border:1px solid black;"><strong><a href="/company'+element.id+'" "target="_blank">'+name+'</a></strong>';
		e_html += '<br></br><br></br>'
		e_html += '<div>'
		e_html += '<input type="hidden" name="index" value="'+index+'" id="index_'+id+'"/>';
		e_html += '<input type="hidden" name="topic_name" value="'+name+'" id="topic_name_'+id+'"/>';
		e_html += '<input type="hidden" name="address_guid" value="'+address_guid+'" id="address_guid_'+id+'"/>';
		e_html += '<input type="hidden" name="topic_guid" value="'+guid+'" id="guid_'+id+'"/>';
		//e_html += sec_element_html(id, 'Website', 'http://');
		e_html += '</div>';
		e_html += '<br></br>'
		e_html += e_box_text;
		e_html += '</div>';
		e_html += '<input type="submit" id="submit_'+id+'" value="submit" /> <input type="button" id="skip_'+id+'" value="Skip" />'
		e_html += '<br></br><br></br>';
		e_html += '<div id="map_canvas_'+index+'" style="width: 500px; height: 300px"></div>'
		e_html += '</div>';
		parent_list.append($(e_html));
		//comp_html += '<br></br>'
	}
	else
	{
		e_html += '<div style="width:820px;border:1px solid black; "><strong><font size="4" style="font-family:Verdana, Arial, Helvetica, sans-serif"><a href="/company'+element.id+'" "target="_blank">'+name+'</a></font></strong><img src="" alt="" name="thumb" id="thumb" align="middle"><div id="description"></div>';
		e_html += '<div id="span_headquarters_'+index+'" ><span></span></div>';
		e_html += '<br></br><br></br>';
		e_html += '<div id="map_canvas_1" style="width: 720px; height: 180px"></div>'
		e_html += '<input type="hidden" name="index" value="'+index+'" id="index_'+id+'"/>';
		e_html += '<input type="hidden" name="topic_name" value="'+name+'" id="topic_name_'+id+'"/>';
		e_html += '<input type="hidden" name="address_guid" value="'+address_guid+'" id="address_guid_'+id+'"/>';
		e_html += '<input type="hidden" name="topic_guid" value="'+guid+'" id="guid_'+id+'"/>';
		/*e_html += '<input type="text" name="street" value="" id="street_'+id+'"/>';
		e_html += '<input type="text" name="city" value="" id="city_'+id+'"/>';
		e_html += '<input type="text" name="state" value="" id="state_'+id+'"/>';
		e_html += '<input type="text" name="postcode" value="" id="postcode_'+id+'"/>';*/
		
		e_html += '</div>';
		
		//e_html += e_box_text;
		e_html += '<input type="submit" id="submit_'+id+'" value="submit" disabled="disabled" /> <input type="button" id="skip_'+id+'" value="Skip" />';
		e_html += '<br></br>';
		e_html += '<br></br>';
		e_html += '</div>';
		parent_list.append($(e_html));
		var topic_domain = '/base/bioventurist/science_or_technology_company';
		jsonp_totalblurb_freebase("freebase.com", name, topic_domain, 500,
				function(m){
					$("#thumb").attr('src','http://'+"{{domain_used}}"+'/api/trans/image_thumb'+m.result[0].image.id);
				},
				function(m){
					$("#description").append($('<span>'+m.result.body+'</span>'));
				},
				function(m){
					var test = 0;
					
				}
			);
		createHeadquarters_edit("span_headquarters_"+index, name, type, element.id, '', "{{domain_used}}", url_read,true);
		
	}
	final_element_index = final_element_index + 1;
	
	
	var geocoder = null;
	var point_val = null;
	if( !flag)
	{
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById('map_canvas_'+index));
			map.setCenter(new GLatLng(37.4419, -122.1419), 13);
			geocoder = new GClientGeocoder();
			map.enableScrollWheelZoom();

		  }
	}
	geocoder = new GClientGeocoder();
	//map = new GMap2(document.getElementById("map_container"));
    //map.setCenter(new GLatLng(37,-97),3);
    //map.addControl(new GLargeMapControl());
	//map.addControl(new GMapTypeControl());
	//map.addControl(new GOverviewMapControl(new GSize(90,90)));
	
	//map.addMapType(G_PHYSICAL_MAP);
	//map.addMapType(G_NORMAL_MAP); 
	//map.addMapType(G_SATELLITE_MAP);
	if(!flag)
	{
		showAddress(address);
	}
	function showAddress(address) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
			  point_val = point;
              map.setCenter(point, 13);
              marker = new GMarker(point,{'draggable':true});
              map.addOverlay(marker);
			  marker.openInfoWindowHtml(address);
	  
			  
            }
          }
        );
      }
    }
	

	// Bind controllers to the buttons:
	$('#submit_'+id).bind('click',
		function (e,data) {
			// Get the current topic's freebase topic_id
			var html_id = $(this).get(0).id;
			html_id = html_id.replace(/submit_/, "");							
			var topic_guid = $('#guid_'+html_id).val();
			var topic_name = $('#topic_name_'+html_id).val();
			var address_guid = $('#address_guid_'+id).val();
			
			// Format the data and write to freebase:
			var vals_to_add = new Array();

			var geo_to_add = new Object();
			geo_to_add['type'] = 'link';
			geo_to_add['topic1'] = new Object();
			geo_to_add['topic1']['guid'] = address_guid;
			geo_to_add['topic2'] = new Array();
			
			// Create a new geolocation
			var geo_element = new Object();
			geo_element.guid = 'n/a';
			geo_element.id = 'n/a';
			geo_element.type = '"/location/geocode"';
			geo_element.name = '';
			geo_element.create_new = 'true';
			var topic2 = geo_to_add['topic2'];
			topic2[0] = new Object();
			geo_to_add['topic2'][0] = geo_element;				
			geo_to_add['topic2'][0]['topic1_property'] = "/location/location/geolocation";				
			geo_to_add['topic2'][0]['type'] = '"/location/geocode"';
			geo_to_add['topic2'][0]['elements_to_add'] = new Array();				
			geo_to_add['topic2'][0]['force_create'] = 'true';									
			
			// Add lat and long:
			var val_to_add = new Object();
			val_to_add['type'] = 'primitive';
			val_to_add['topic1'] = new Object();
			val_to_add['topic1']['guid'] = 'n/a';
			val_to_add['topic2'] = new Array();
			var topic2 = val_to_add['topic2'];
			topic2[0] = new Object();
				  
			point_val=marker.getLatLng();
			// Lat
			addLocationElement(0, val_to_add, point_val.y);
			//long
			addLocationElement(1, val_to_add, point_val.x);
			
			geo_to_add['topic2'][0]['elements_to_add'].push(val_to_add);	
			vals_to_add.push(geo_to_add);
			
			// If we have any new values:
			if(vals_to_add.length > 0){	
				var vals_to_remove = new Array(); // dummy vals
				
				var transmit_data = new Object();	
				transmit_data["vals_to_add"] = JSON.stringify(vals_to_add);
				transmit_data["vals_to_remove"] = JSON.stringify(vals_to_remove);
				var post_command = '/topic_info/write_mixed/'; 
				
				$.ajax({
					type: "POST",
					url: post_command + 'na' + '/',
					data: transmit_data,
					success: function(m) {
						
					},
					error: function(m) {
						
					},
					dataType: "text",
					cache: false
				});		
			}		
						
				//Move to the next element
				if(flag)
				{
					exchangeElement(html_id,element_list, properties, indexes, display_num,flag);
				}
				else
				{
					exchangeElement(html_id,element_list, properties, indexes, display_num);
				}
		}
	);
	        	
	// Bind controllers to the buttons:
	$('#skip_'+id).bind('click',
		function (e,data) {
			//var active = .accordion('option', 'active');
			
			//Move to the next element
			var html_id = $(this).get(0).id;
			html_id = html_id.replace(/skip_/, "");	
			
			$('#id_'+id).fadeOut(1000, function () {
        		if(flag)
				{
//				
					
					exchangeElement(html_id,element_list, properties, indexes, display_num,'skip');
					
					
				}
				else
				{
					exchangeElement(html_id,element_list, properties, indexes, display_num);
				}
      		});
		}
	);
	
}

/**
 * location_index = 0: lat
 * location_index = 1: long
 */
function addLocationElement(location_index, val_to_add, location_value){
	var val = new Object();
	val.guid = '';
	val.id = '';
	val.type = '';
	val.name = ''+location_value;
	val.create_new = 'false';
	val.elements_to_add = new Array();
	val_to_add['topic2'][location_index] = val;
	val_to_add['topic2'][location_index]['type'] = "/type/float";
	val_to_add['topic2'][location_index]['elements_to_add'] = new Array();				
	val_to_add['topic2'][location_index]['force_create'] = 'false';									

	if(location_index == 0){
			val_to_add['topic2'][location_index]['topic1_property'] = "/location/geocode/latitude";					
	} else {
			val_to_add['topic2'][location_index]['topic1_property'] = "/location/geocode/longitude";				
	}	
}
function replaceAll(text, strA, strB) {
    return text.replace(new RegExp(strA,"g"), strB);
}

function getAddress(hq){
	var headquarters = '';
	if(hq.street_address.length > 0){
		headquarters += (typeof(hq.street_address) != "undefined" && hq.street_address != null ? hq.street_address[0] + "," : "" );
	}
	if(hq.citytown != null){
		headquarters += (typeof(hq.citytown.name) != "undefined" && hq.citytown.name != null ? hq.citytown.name + "," : "" );				
	}
	if(hq.state_province_region != null){
		headquarters += (typeof(hq.state_province_region.name) != "undefined" && hq.state_province_region.name != null ? hq.state_province_region.name + "," : "" );				
	}
	if(hq.postal_code != null ){
		headquarters += (typeof(hq.postal_code.name) != "undefined" && hq.postal_code.name != null ? hq.postal_code.name : "" );				
	}
	return headquarters;
}

/* 
Removes the given element, and places another one at the bottom of the queue.
 */
function exchangeElement(id,element_list,properties, indexes, display_num,flag){
	//var new_index = parseFloat($('#index_'+id).val()) + 1;
	new_index++;
	if(flag =='skip'){
		var num_remaining_topics = $("#num_companies").text();
		addElement(element_list, properties, indexes_array[new_index], display_num,flag);
	}
	$('#id_'+id).remove();
	if(flag && flag !='skip'){
		var num_remaining_topics = $("#num_companies").text();
		$("#num_companies").text(num_remaining_topics-1);
		addElement(element_list, properties, indexes_array[new_index], display_num,flag);
	}
	
	if(! flag)
	{
		var num_remaining_topics = $("#num_topics").text();
	//$("#num_topics").text(''+num_remaining_topics);
		$("#num_topics").text(num_remaining_topics-1);
		addElement(element_list, properties, indexes);
	}
	
	return final_element_index;
}
 
function write_to_freebase(post_command, topic1_guid, topic1_property, topic2_name, topic2_id){
	// Write the data to freebase:
	var data = new Object();
	data["topic1_id"] = topic1_guid;
    data["topic1_property"] = topic1_property;
	data["topic2_add_names"] = topic2_name;
    data["topic2_add_ids"] = topic2_id;
    data["topic2_create_new"] = "false";
    data["topic2_remove_ids"] = "";
    data["topic2_type"] = "";
    data["topic2_type_for_create"] = "";
	
	$.ajax({
		type: "POST",
		url: post_command,
		data: data,
		success: function(m) {
			if (console && console.log) {
				console.log(m);
				perform_touch(freebase_domain);
			}
		},
		error: function(m) {
		},
		dataType: "text",
		cache: false
	});	

}

function fisherYates ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}